package org.itboys.mobile.service.mysql.mobile.order;


import org.apache.commons.lang3.StringUtils;
import org.itboys.commons.ErrorException;
import org.itboys.commons.utils.time.TimeUtils;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.framework.resource.ResourceHolder;
import org.itboys.kitchen.dao.order.KitchenOrderProductMapper;
import org.itboys.kitchen.entity.mysql.income.KitchenIncomeRecord;
import org.itboys.kitchen.entity.mysql.order.KitchenOrder;
import org.itboys.kitchen.entity.mysql.order.KitchenOrderProduct;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.dao.product.SundayProductMapper;
import org.itboys.mobile.dao.promotion.SundayCouponMapper;
import org.itboys.mobile.dto.count.KitchenCountDto;
import org.itboys.mobile.dto.count.KitchenCountProductDto;
import org.itboys.mobile.dto.order.KitchenOrderDto;
import org.itboys.mobile.dto.order.KitchenOrderProductDto;
import org.itboys.mobile.entity.mongo.SundayAddress;
import org.itboys.mobile.entity.mongo.SundayCid;
import org.itboys.mobile.entity.mongo.SundayMember;
import org.itboys.mobile.entity.mysql.product.SundayProduct;
import org.itboys.mobile.entity.mysql.promotion.SundayCoupon;
import org.itboys.mobile.service.mongo.mobile.*;
import org.itboys.mobile.service.mysql.mobile.income.KitchenMobileIncomeService;
import org.itboys.mobile.service.mysql.mobile.score.SundayMobileScoreService;
import org.itboys.mobile.service.pos.PosOrderService;
import org.itboys.mobile.util.DatetUtil;
import org.itboys.mobile.util.NumberUtil;
import org.itboys.mobile.util.getui.GeTuiUtil;
import org.itboys.mongodb.service.BaseMySqlService;
import org.itboys.param.ParamUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * 作者：jiangxiong
 * 日期：2017年5月8日
 * 联系方式 ：empty90911@126.com
 * 描述：农厨_订单_service_mobile
 */
@Service
public class KitchenMobileOrderService extends BaseMySqlService<KitchenOrder> {
    @Autowired
    private KitchenMobileCountService countService;
    @Autowired
    private SundayMobileAddressService addressService;

    @Autowired
    private KitchenOrderProductMapper orderProductMapper;
    @Autowired
    private SundayProductMapper productMapper;
    @Autowired
    private SundayMobileMemberService memberService;
    @Autowired
    private KitchenMobileCartService cartService;
    @Autowired
    private ResourceHolder resourceHolder;
    @Autowired
    private KitchenMobileIncomeService incomeService; ;
    @Autowired
    private SundayMobileScoreService scoreService;
    @Autowired
    private SundayCouponMapper couponMapper;
    @Autowired
    private SundayMobileCommentService commentService;
    @Autowired
    private SundayMobileCidService cidService;
    @Autowired
    private SundayMobilePermissionService permissionService;
    @Autowired
    private PosOrderService posOrderService;
    /**
     * 创建订单 商城，积分，采购。双版本通用
     * @param memberId
     * @param cartIds
     * @param sendType
     * @param couponId
     * @param isUsedBalance
     * @param addressId
     * @param villageId
     * @param payPassword
     */
    @Transactional
    public Map<String,Object> createOrder(Long memberId,List<Long> cartIds,
                            Integer sendType,Long couponId,Integer isUsedBalance,Long addressId,Long villageId,
                            String payPassword,String remark){

        Map<String,Object> result = new HashMap<String,Object>();




        //返回数据
       // String payAmount ="";//本次付款金额
        String orderIds = "";//需要支付的订单
        String receiveName="";//收获信息
        String receiveMobile="";//收获信息
        String receiveAddress="";//收获信息
        Integer isNeedToPay=1;//订单是否需要支付。默认是
        SundayAddress address = null;
        String orderNo=null;
        //1校验参数签名
        //2获取购物车数据
        KitchenCountDto countDto =countService.countCart(memberId,cartIds,isUsedBalance,couponId,null,sendType,villageId);
        //准备订单数据
        KitchenOrder order = new KitchenOrder();
        SundayMember member = memberService.getById(memberId);
        //2.1，商城订单
        if(countDto.getType()==SundayCommonConstants.type_mall){
            logger.info("--订单开始生成--商城订单");
            if(sendType==null){
                throw new ErrorException("请选择配送方式。");
            }
            orderNo=NumberUtil.generateNumber("MALL");

            //1，判断收货方式
            order.setSendType(countDto.getSendType());
            order.setSendAmount(countDto.getSendAmount());

            //门店配送
            if(sendType==SundayCommonConstants.send_type_send){
                if(!LongUtil.isNotZreo(addressId)){
                    throw new ErrorException("门店配送需要填写收货地址。");

                   }

                address = addressService.getById(addressId);
                //2017年9月8日
                if(StringUtils.isEmpty(address.getReceiveAddress())){
                    throw new ErrorException("门店配送需要具体的门牌号码。");
                }
                receiveName=address.getReceiveName();
                receiveMobile=address.getReceiveMobile();
                //商城订单收货地址：市-小区-详细地址
                receiveAddress=address.getCityName()+address.getVillageName()+address.getReceiveAddress();

            //自提
            }else{
                receiveName=member.getNickName();
                receiveMobile=member.getMobile();
                receiveAddress="【自提地址：】"+countDto.getSendAddress();
            }
            //2，判断是否使用余额

            if(isUsedBalance==1){
                //2.0，是否输入支付密码
                if(org.apache.commons.lang.StringUtils.isEmpty(payPassword)){
                    throw new ErrorException("请输入支付密码");
                }
                //2.1,校验支付密码
                memberService.checkPayPassWord(memberId,payPassword);
                //2.1,扣减用户余额
                /*if(countDto.getUsedBalance().compareTo(new BigDecimal("0"))==1){
                    memberService.changeBalance(Long memberId,
                            Integer type,
                            String orderNo,
                            BigDecimal payAmount,
                           null,
                            null);
                }*/
            /*   incomeService.generateRecord(memberId, SundayCommonConstants.income_record_type_consume,
                        orderNo,countDto.getUsedBalance());
                order.setBalancePayAmount(countDto.getUsedBalance());*/

            }
            //3，判断订单是否需要支付
            if(countDto.getPayAmount().compareTo(new BigDecimal("0"))==0){
                logger.info("商城订单--"+orderNo+"不需要支付，开始创建");
                isNeedToPay=0;
                order.setOrderStatus(SundayCommonConstants.ORDER_STATUS_DPS);
              /*  if(sendType==SundayCommonConstants.send_type_send){
                    order.setOrderStatus(SundayCommonConstants.ORDER_STATUS_DPS);
                }else if(sendType==SundayCommonConstants.send_type_self){
                    order.setOrderStatus(SundayCommonConstants.ORDER_STATUS_PSZ);
                }*/


            }else{
                logger.info("商城订单--"+orderNo+"需要支付，开始创建");
                isNeedToPay=1;
                order.setOrderStatus(SundayCommonConstants.ORDER_STATUS_DFK);
            }
            //4，修改优惠券状态
            if(LongUtil.isNotZreo(couponId)){

                SundayCoupon coupon= new SundayCoupon();
                coupon.setId(couponId);
                coupon.setStatus(SundayCommonConstants.counpon_status_ysy);
                couponMapper.update(coupon);
            }
            //只有商城订单才有门店信息
            order.setShopId(countDto.getShopId());
            order.setShopName(countDto.getShopName());
        }
        //2.2，积分订单
        if(countDto.getType()== SundayCommonConstants.type_score){
            logger.info("--订单开始生成--积分订单");
            orderNo=NumberUtil.generateNumber("SCO");
            //判断收货地址
            if(!LongUtil.isNotZreo(addressId)){
                throw new ErrorException("请选择收货地址");
            }
            //判断用户积分是否充足
            if(countDto.getScore().compareTo(countDto.getPayAmount())==-1){
                throw new ErrorException("当前可用积分："+countDto.getScore()+"分");
            }
            //生成积分交易明细
            //scoreService.generateRecord(orderNo, countDto.getPayAmount(),SundayCommonConstants.SCORE_TYPE_BUY,memberId);

            address = addressService.getById(addressId);
            //积分订单不需要支付
            isNeedToPay=0;
            order.setOrderStatus(SundayCommonConstants.ORDER_STATUS_DPS);
            receiveName=address.getReceiveName();
            receiveMobile=address.getReceiveMobile();
            //积分订单收货地址需要包含省市区县数据
            receiveAddress=address.getCityName()+address.getVillageName()+address.getReceiveAddress();

        }
        //2.3，采购订单
        if(countDto.getType()== SundayCommonConstants.type_caigou){
            logger.info("--订单开始生成--采购订单");
            orderNo=NumberUtil.generateNumber("CG");
            if(!LongUtil.isNotZreo(addressId)){
                throw new ErrorException("请选择收货地址");
            }
            address = addressService.getById(addressId);
            //采购订单不需要支付
            isNeedToPay=0;
            order.setOrderStatus(SundayCommonConstants.ORDER_STATUS_DPS);
            order.setIsAccount(0);

            receiveName=address.getReceiveName();
            receiveMobile=address.getReceiveMobile();
            //采购订单收货地址需要包含省市区县数据
            receiveAddress=address.getProvinceName()+address.getCityName()+address.getDistrictName()+address.getReceiveAddress();
            //返回需要支付的订单IDs。只针对需要支付的订单
            //采购订单-保持用户类型
            order.setUserType(member.getUserType());
        }

        order.setOrderNo(orderNo);
        order.setType(countDto.getType());
        order.setTotalAmount(countDto.getTotalAmount());
        order.setPayAmount(countDto.getPayAmount());
        order.setCostAmount(countDto.getCostAmount());
        order.setReceiveName(receiveName);
        order.setReceiveMobile(receiveMobile);
        order.setReceiveAddress(receiveAddress);
        order.setMemberId(member.getId());
        order.setMemberName(member.getNickName());
        order.setRemark(remark);
        order.setPromotionMsg(countDto.getMsg());

        order.setVillageId(countDto.getVillageId());
        order.setVillageName(countDto.getVillageName());
        order.setCouponId(countDto.getCouponId());
        order.setCouponAmount(countDto.getCouponAmount());
        order.setBalancePayAmount(countDto.getUsedBalance());
        //保存订单
        super.insert(order);
        //保存订单商品
        List<Long> productIds=new ArrayList<Long>();
        //本次销售的商品数量
        List<Integer> sale_nums=new ArrayList<Integer>();
  /*      logger.info("--countDto"+countDto.getTypeStr());
        logger.info("--countDto-products"+countDto.getProducts().size());*/
        List<KitchenOrderProduct> orderProducts = new ArrayList<KitchenOrderProduct>();
        for(KitchenCountProductDto countProductDto:countDto.getProducts()){
            KitchenOrderProduct orderProduct =
                    new KitchenOrderProduct(order.getId(),countProductDto.getId(),
                            countProductDto.getPrice(), countProductDto.getCostPrice(),countProductDto.getName(),countProductDto.getNumber(),
                            countProductDto.getImage(),
                            countProductDto.getStandard(),countProductDto.getNum(), countProductDto.getType(),countProductDto.getItemCode());
            orderProductMapper.insert(orderProduct);
            productIds.add(orderProduct.getProductId());
            sale_nums.add(orderProduct.getNum());
            orderProducts.add(orderProduct);
        }
        //更新商品销量
        if(ListUtil.isNotNull(productIds)){
            Map<String,Object> param = new HashMap<String,Object>();
            param.put("ids",productIds);
            List<SundayProduct> products = productMapper.select(param);

            for(SundayProduct product:products){
              //  boolean isExist = false;
                for(KitchenCountProductDto countProductDto:countDto.getProducts()){
                    if(product.getId().longValue()==countProductDto.getId()){
                        product.setSaleNumber(product.getSaleNumber()+countProductDto.getNum());
                        break;
                    }
                }
                productMapper.update(product);

            }

        }
        //删除购物车
       cartService.deleteCart(cartIds,memberId,null);
        //返回支付的订单ID集合
        if(isNeedToPay==1){
            orderIds=order.getId().toString();
        }
        //推送不需要付款的商城订单给门店APP
        if(order.getType()==SundayCommonConstants.type_mall&&
                order.getOrderStatus()==SundayCommonConstants.ORDER_STATUS_DPS){
          List<SundayCid> cids = cidService.findByMemberId(order.getShopId(),null);
          for(SundayCid cid:cids){
            GeTuiUtil.sendMessage(cid,
                      "您有新的花果山果蔬订单需要配送", 1,null);
          }

        }

        //2017年8月27日，pos相关
        //1，扣减库存。
        if(order.getType()==SundayCommonConstants.type_mall){
            permissionService.changeStore(productIds,sale_nums,order.getShopId());
        }
        //2，变更用户积分和余额
        if(order.getType()==SundayCommonConstants.type_mall&&
                order.getBalancePayAmount()!=null&&
                order.getBalancePayAmount().compareTo(new BigDecimal("0"))==1){
                memberService.changeBalance(memberId,SundayCommonConstants.income_record_type_consume,
                        orderNo,order.getBalancePayAmount(),null,null);
        }
        if(order.getType()==SundayCommonConstants.type_score){
            memberService.changeScore(orderNo,order.getPayAmount(), SundayCommonConstants.SCORE_TYPE_BUY,memberId);
        }

        //3，推送pos订单
        if(order.getType()==SundayCommonConstants.type_mall&&
                order.getSendType()==SundayCommonConstants.send_type_send&&
                order.getOrderStatus()==SundayCommonConstants.ORDER_STATUS_DPS){
            SundayMember shop = memberService.getById(order.getShopId());
            posOrderService.processOrderToPos(order.getId());
        }

        result.put("payAmount",countDto.getPayAmount());//本次付款金额
        result.put("orderIds",orderIds);//需要支付的订单
        result.put("receiveName",receiveName);//收获信息
        result.put("receiveMobile",receiveMobile);//收获信息
        result.put("receiveAddress",receiveAddress);//收获信息
        result.put("isNeedToPay",isNeedToPay);//订单是否需要支付
        result.put("type",1);//1,订单2,余额充值
        result.put("info","isNeedToPay标识是否需要支付。0否，1是。type是标识支付订单类型，1是订单，2是余额充值");
        return result;
    }

    /**
     * 分页获取订单
     * @param request
     * @param memberId
     * @param type,1,用户自己的商城订单，2用户自己的积分订单，3，门店/大客户自己的采购订单，4，门店的配送订单
     * @param orderStatuses 0，全部，1,待付款，2待配送，3配送中，4待评价，
     * @return
     */
    public List<KitchenOrderDto> selectOrder(HttpServletRequest request,Long memberId,Integer type,List<Integer> orderStatuses){
        Map<String,Object> param = ParamUtil.packageMysqlPageParam(request,"orderNo","createTime_start","createTime_end");
        //memberId=2l;
        //门店的配送订单
        if(type==4){
            //判断是否登陆的是门店员工账号。员工账号和门店查看一样的数据
            SundayMember shopEmployee = memberService.getById(memberId);
            if(LongUtil.isNotZreo(shopEmployee.getParentId())){
                memberId=shopEmployee.getParentId();
            }
            param.put("shopId",memberId);
            param.put("type",SundayCommonConstants.type_mall);
        }else{
            param.put("memberId",memberId);
            param.put("type",type);
        }
        if(ListUtil.isNotNull(orderStatuses)){
            if(orderStatuses.get(0)!=0){
                param.put("orderStatuses",orderStatuses);
            }
        }
       return pakageDtoMuilt(super.select(param));
    }

    /**
     * 查询订单详情
     * @param orderId
     * @param memberId
     * @return
     */
    public KitchenOrderDto findOne(Long orderId,Long memberId){
        return pakageDtoSingle(super.find(orderId),null);
    }
    /**
     * 取消订单
     * @param orderId
     * @param memberId
     * @return
     */
    public void cancelOrder(Long orderId,Long memberId){

        KitchenOrder order= super.find(orderId);
            //用户的商城订单，待付款允许取消
        String msg=null;
        if(order.getType()==SundayCommonConstants.type_mall&&order.getOrderStatus()!=SundayCommonConstants.ORDER_STATUS_DFK){
            msg="非待付款订单，不能取消";
        }else if(order.getType()==SundayCommonConstants.type_score){
            msg="积分订单不能取消";
        }else if(order.getType()==SundayCommonConstants.type_caigou&&order.getOrderStatus()!=SundayCommonConstants.ORDER_STATUS_DPS){
            msg="非待配送订单，不能取消";
        }
        if(StringUtils.isNotEmpty(msg)){
            throw new ErrorException(msg);
        }
        order.setOrderStatus(SundayCommonConstants.ORDER_STATUS_YQX);
        //商城订单，返回用户余额抵扣部分
        if(order.getType()==SundayCommonConstants.type_mall&&
                order.getBalancePayAmount()!=null&&order.getBalancePayAmount().compareTo(new BigDecimal("0"))==1){
           memberService.changeBalance(order.getMemberId(),
                  SundayCommonConstants.income_record_type_cancel,
                   order.getOrderNo(),
                  order.getBalancePayAmount(),
                  null,
                  null);
        }
        super.update(order);
    }
    /**
     * 确认收货
     * @param orderId
     * @param memberId
     * @return
     */
    @Transactional
    public void confirmReceive(Long orderId,Long memberId){


        KitchenOrder order=checkOrder(orderId,SundayCommonConstants.ORDER_STATUS_PSZ,"非配送中订单，不能确认收货",memberId);
        order.setOrderStatus(SundayCommonConstants.ORDER_STATUS_YSH);
        order.setReceiveTime(new Date());

        //生成收益，
        //生成用户赠送积分(实付款+余额抵扣)
        if(order.getType()==SundayCommonConstants.type_mall){
            //SundayScoreConfig scoreConfig =scoreConfigService.findOne(null);
            BigDecimal thisAmount = order.getPayAmount();
            if(order.getBalancePayAmount()!=null){
                thisAmount.add(order.getBalancePayAmount());
            }
            memberService.changeScore(order.getOrderNo(),thisAmount, SundayCommonConstants.SCORE_TYPE_REWARD,memberId);
        }
            super.update(order);
    }

    /**
     * 商城订单发货(门店发货)
     * @param orderId
     * @param driverId
     * @param memberId
     */
    @Transactional
    public void sendOrder(Long orderId,Long driverId, Long memberId){





        KitchenOrder order=checkOrder(orderId,SundayCommonConstants.ORDER_STATUS_DPS,"非待配送订单，不能发货",null);
        order.setOrderStatus(SundayCommonConstants.ORDER_STATUS_PSZ);
        order.setSendTime(new Date());
        //设置配送员信息(非)
        if(LongUtil.isNotZreo(driverId)){
            SundayMember driver =memberService.getById(driverId);
            order.setDriverId(driver.getId());
            order.setDriverName(driver.getNickName());
            order.setDriverMobile(driver.getMobile());
        }
        //memberId作为(员工)经办人
        if(LongUtil.isNotZreo(memberId)){
            SundayMember member =memberService.getById(memberId);
            order.setHandleId(memberId);
            order.setHandleName(member.getNickName());
        }
        super.update(order);
    }

    /**
     * 评论订单
     * @param orderId
     * @param productIds
     * @param contents
     * @param scores
     * @param images 图片集合，固定大小=productIds集合大小*3。。每个商品限制最大传入三张，没有图片的使用noImage字符传固定值。
     * @param memberId
     */
    public void  commentOrder(Long orderId,List<Long> productIds,List<String> contents,List<Integer> scores,List<String> images,Long memberId,String nonce, String sign){


            //2017年6月20日，验证签名
           /* Map<String, Object> param =new HashMap<String,Object>();
            param.put("orderId",orderId);
            param.put("driverId",driverId);
            param.put("nonce", nonce);
            param.put("sign", sign);
            boolean signSer = MobileSignUtils.signCheck(param, sign);
            if(!signSer){
                logger.warn("签名校验失败");
                throw new ErrorException("签名校验失败");
            }*/



           String msg ="";
            if(ListUtil.isNull(productIds)||ListUtil.isNull(contents)||ListUtil.isNull(scores)){
                msg="评论接口参数有错误(为空)";
            }
            if(productIds.size()!=contents.size()||productIds.size()!=scores.size()||contents.size()!=scores.size()){
                msg="评论接口参数有错误（参数不对应）";
            }
            if(productIds.size()*3!=images.size()){
                msg="评论接口参数有错误（图片参数）";
            }
            if(msg!=""){
                throw new ErrorException(msg);
            }


        KitchenOrder order=checkOrder(orderId,SundayCommonConstants.ORDER_STATUS_YSH,"非待评论订单，不能评论",memberId);
            SundayMember member = memberService.getById(memberId);
            commentService.generateComment(productIds,
                    contents,
                    scores,
                    images,
                    memberId,
                    member.getImage(),
                    member.getNickName(),
                    SundayProduct.class.getSimpleName());

            //更改订单状态
            order.setOrderStatus(SundayCommonConstants.ORDER_STATUS_YPJ);
            super.update(order);

    }




    /**
     * 校验订单信息
     * @param orderId
     * @param status
     * @param msg
     * @param memberId
     * @return
     */
    public KitchenOrder checkOrder(Long orderId,Integer status,String msg,Long memberId){
        KitchenOrder order =super.find(orderId);
        if(status!=null&&order.getOrderStatus()!=status){
                throw new ErrorException(msg);
        }
        if(LongUtil.isNotZreo(memberId)&&order.getMemberId().longValue()!=memberId){
            throw new ErrorException("数据错误，请重试");
        }
        return order;
    }

    /**
     * 获取各订单状态的数量
     * @param memberId
     * @return
     */
    public Map<String,Object> getOrderNumber(Long memberId){
        Map<String,Object> result = new HashMap<String,Object>();
        Integer dfk=0;
        Integer dps=0;
        Integer psz=0;
        Integer dpj=0;
        String msg="dfk(待付款)，dps(待配送)，psz(配送中)，dpj(待评价)";


        Map<String,Object> param = new HashMap<String,Object>();
        List<Integer> orderStatuses = new ArrayList<Integer>();
        SundayMember member = memberService.getById(memberId);
        if(member.getUserType()==SundayCommonConstants.user_type_member){
            param.put("memberId",memberId);
        }else{
            if(LongUtil.isNotZreo(member.getParentId())){
                memberId=member.getParentId();
            }
            param.put("shopId",memberId);
        }
        orderStatuses.add(SundayCommonConstants.ORDER_STATUS_DFK);
        orderStatuses.add(SundayCommonConstants.ORDER_STATUS_DPS);
        orderStatuses.add(SundayCommonConstants.ORDER_STATUS_PSZ);
        orderStatuses.add(SundayCommonConstants.ORDER_STATUS_YSH);
        List<KitchenOrder> orders = super.select(param);
        for(KitchenOrder order:orders){
            if(order.getOrderStatus()==SundayCommonConstants.ORDER_STATUS_DFK){
                dfk++;
            }else if(order.getOrderStatus()==SundayCommonConstants.ORDER_STATUS_DPS){
                dps++;
            }else if(order.getOrderStatus()==SundayCommonConstants.ORDER_STATUS_PSZ){
                psz++;
            }else if(order.getOrderStatus()==SundayCommonConstants.ORDER_STATUS_YSH){
                dpj++;
            }
        }




        result.put("dfk",dfk);
        result.put("dps",dps);
        result.put("psz",psz);
        result.put("dpj",dpj);
        result.put("msg",msg);

        return result;
    }
    /**
     * 获取营收
     * @param memberId
     * @return
     */
    /**
     *
     * @param memberId
     * @param type 1,获取今日信息（销售订单和销售总额）2，获取总收益，总销售订单，总销售总额，采购实付总金额，采购实付金额
     * @return
     */
    public Map<String,Object> getRevenue(Long memberId,Integer type){
        Map<String,Object> result = new HashMap<String,Object>();

        Integer jrxsdd=0;
        String jrxsze="0";

        Integer xsdd=0;
        String xsze="0";
        String cgddsfje="0";
        String cgddyfje="0";
        Integer cdddsl=0;
        String revenue="0";//总收益=采购订单零售价格-采购订单实付
        String msg="jrxsdd(今日销售订单数)，jrxsze(今日销售总额)，" +
                    "xsdd(销售订单数)，xsze（销售总额）"+"cgddsfje(采购实付总金额)，cgddyfje(采购应付总金额),cdddsl(采购订单数),revenue(总收益)";
        Map<String,Object> param = new HashMap<String,Object>();
        List<Integer> orderStatuses = new ArrayList<Integer>();
        orderStatuses.add(SundayCommonConstants.ORDER_STATUS_DPS);
        orderStatuses.add(SundayCommonConstants.ORDER_STATUS_PSZ);
        orderStatuses.add(SundayCommonConstants.ORDER_STATUS_YSH);
        orderStatuses.add(SundayCommonConstants.ORDER_STATUS_YPJ);
        param.put("orderStatuses",orderStatuses);
        List<KitchenOrder> orders = new ArrayList<KitchenOrder>();

        //今日销售信息
        if(type==1){

          param.put("createTime_start",TimeUtils.formatToTime(DatetUtil.setDateStart(new Date())));
          param.put("createTime_end",TimeUtils.formatToTime(DatetUtil.setDateEnd(new Date())));
          param.put("shopId",memberId);
          orders=super.select(param);
          Double jrxszeDou=0.00;
           for(KitchenOrder order:orders){
               jrxsdd++;
               jrxszeDou+=order.getPayAmount().doubleValue();
               if(order.getBalancePayAmount()!=null){
                   jrxszeDou+=order.getBalancePayAmount().doubleValue();
               }
               if(order.getCouponAmount()!=null){
                   jrxszeDou+=order.getCouponAmount().doubleValue();
               }
           }
            jrxsze=new BigDecimal(jrxszeDou).setScale(2,BigDecimal.ROUND_HALF_UP).toString();
            //总的信息,含销售和采购信息
        }else if(type==2){

            param.put("shopId_or_memberId",memberId);
            //采购应付间采购实付
            orders=super.select(param);
            Double xszeDou=0.00;
            Double cgddsfjeDou=0.00;
            Double  cgddyfjeDou=0.00;
            for(KitchenOrder order:orders){
                if(order.getType()==SundayCommonConstants.type_caigou){
                    cdddsl++;
                    cgddsfjeDou+=order.getPayAmount().doubleValue();
                    //可以有些数据的订单零售价是空
                   if(order.getCostAmount()!=null){
                        cgddyfjeDou+=order.getCostAmount().doubleValue();
                    }

                }
                if(order.getType()==SundayCommonConstants.type_mall){
                    xsdd++;
                    xszeDou+=order.getPayAmount().doubleValue();
                    if(order.getBalancePayAmount()!=null){
                        xszeDou+=order.getBalancePayAmount().doubleValue();
                    }
                    if(order.getCouponAmount()!=null){
                        xszeDou+=order.getCouponAmount().doubleValue();
                    }
                }
            }
            cgddsfje=new BigDecimal(cgddsfjeDou).setScale(2,BigDecimal.ROUND_HALF_UP).toString();
            cgddyfje=new BigDecimal(cgddyfjeDou).setScale(2,BigDecimal.ROUND_HALF_UP).toString();

            xsze=new BigDecimal(xszeDou).setScale(2,BigDecimal.ROUND_HALF_UP).toString();

            revenue=new BigDecimal(cgddyfjeDou-cgddsfjeDou).setScale(2,BigDecimal.ROUND_HALF_UP).toString();

        }


        //type==1返回
        result.put("jrxsdd",jrxsdd);
        result.put("jrxsze",jrxsze);
        //type==2返回

        result.put("xsdd",xsdd);
        result.put("xsze",xsze);
        result.put("cgddsfje",cgddsfje);
        result.put("cgddyfje",cgddyfje);
        result.put("cdddsl",cdddsl);
        result.put("revenue",revenue);
        result.put("msg",msg);
        return result;
    }

    /**
     * 获取采购和销售明细（分页）
     * @param request
     * @param memberId
     * @param type 1采购明细，2销售明细
     * @return
     */
    public Map<String,Object> getRevenueDetail(HttpServletRequest request,Long memberId,Integer type){
        Map<String,Object> result = new HashMap<String,Object>();
        Map<String,Object> param = ParamUtil.packageMysqlPageParam(request,"createTime_start","createTime_end");
        List< Map<String,Object>> datas = new ArrayList< Map<String,Object>>();
        Double totalAmount=0.00;
        result.put("totalAmount",0.00);
        result.put("datas",datas);

        if(type==1){
            param.put("memberId",memberId);
        }else if(type==2){
            param.put("shopId",memberId);
        }else{
            return  result;
        }
        List<Integer> orderStatuses = new ArrayList<Integer>();
        orderStatuses.add(SundayCommonConstants.ORDER_STATUS_DPS);
        orderStatuses.add(SundayCommonConstants.ORDER_STATUS_PSZ);
        orderStatuses.add(SundayCommonConstants.ORDER_STATUS_YSH);
        orderStatuses.add(SundayCommonConstants.ORDER_STATUS_YPJ);
        param.put("orderStatuses",orderStatuses);
        List<KitchenOrder> orders = super.select(param);

        for(KitchenOrder order:orders){
            Map<String,Object> data = new HashMap<String,Object>();
            data.put("id",order.getId());
            data.put("orderNo",order.getOrderNo());
            //采购订单返回负数的金额
            if(type==1){
                data.put("payAmount",order.getPayAmount().multiply(new BigDecimal("-1")));

            }else{
                data.put("payAmount",order.getPayAmount());

            }
            data.put("memberName","购买人："+order.getMemberName());
            data.put("createTime",order.getCreateTime());
            totalAmount+=order.getPayAmount().doubleValue();
            datas.add(data);
        }

        result.put("totalAmount",new BigDecimal(totalAmount).setScale(2,BigDecimal.ROUND_HALF_UP).toString());
        result.put("datas",datas);
        return result;
    }



    /**
     * 组装DTO
     * @param order
     * @return
     */
    public KitchenOrderDto pakageDtoSingle(KitchenOrder order, List<KitchenOrderProductDto> products){
        if(ListUtil.isNull(products)){
            Map<String,Object> param =new HashMap<String ,Object>();
            param.put("orderId",order.getId());
            products=new ArrayList<KitchenOrderProductDto>();
            for(KitchenOrderProduct orderProduct:orderProductMapper.select(param)){
                if(orderProduct.getOrderId().longValue()==order.getId()){
                    products.add(new KitchenOrderProductDto(
                            orderProduct.getProductId(),orderProduct.getCreateTime(),orderProduct.getCreateDate(),
                            orderProduct.getPrice(), orderProduct.getName(), orderProduct.getNumber(),orderProduct.getImage(),
                            orderProduct.getStandard(), orderProduct.getNum(), orderProduct.getType()));
                }
            }

        }
        String payTime= order.getPayTime()!=null?TimeUtils.format(order.getPayTime(),"yyyy-MM-dd HH:mm:ss"):null;
        String sendTime= order.getSendTime()!=null?TimeUtils.format(order.getSendTime(),"yyyy-MM-dd HH:mm:ss"):null;
        String receiveTime= order.getReceiveTime()!=null?TimeUtils.format(order.getReceiveTime(),"yyyy-MM-dd HH:mm:ss"):null;
        String driverImage = StringUtils.isNoneEmpty(order.getDriverCarNo())?resourceHolder.getStringValue("imgRoot")+order.getDriverImage():null;
        return new KitchenOrderDto(order.getId(),order.getCreateTime(),order.getCreateDate(),
                order.getOrderNo(), order.getType(), order.getTotalAmount(), order.getPayAmount(),
                order.getPayNo(), order.getOrderStatus(), order.getReceiveName(),order.getReceiveMobile(), order.getReceiveAddress(),
                order.getSendType(), order.getSendAmount(),order.getPromotionMsg(),order.getRemark(), order.getShopId(), order.getShopName(),
                order.getDriverId(), order.getDriverName(), order.getDriverMobile(), order.getDriverCarNo(),driverImage,
                payTime,sendTime, receiveTime,  products);

    }
    public List<KitchenOrderDto> pakageDtoMuilt(List<KitchenOrder> orders){
        List<KitchenOrderDto> dtos= new ArrayList<KitchenOrderDto>();
        List<Long> orderIds = new ArrayList<>();
        for(KitchenOrder order:orders){
            orderIds.add(order.getId());
        }
        Map<String,Object> param =new HashMap<String ,Object>();
        param.put("orderIds",orderIds);
        List<KitchenOrderProduct> orderProducts = orderProductMapper.select(param);
        for(KitchenOrder order:orders){
            List<KitchenOrderProductDto> ps = new ArrayList<KitchenOrderProductDto>();
            for(KitchenOrderProduct orderProduct:orderProducts){
                if(orderProduct.getOrderId().longValue()==order.getId()){
                    ps.add(new KitchenOrderProductDto(orderProduct.getProductId(),orderProduct.getCreateTime(),orderProduct.getCreateDate(),
                            orderProduct.getPrice(), orderProduct.getName(), orderProduct.getNumber(),orderProduct.getImage(),
                            orderProduct.getStandard(), orderProduct.getNum(), orderProduct.getType()));
                }
            }
            dtos.add(pakageDtoSingle(order,ps));
        }
        return dtos;
    }
    /**
     * ------------2017年9月7日新增
     */
    /**
     * 商城订单发货(门店发货)PC端
     * @param orderId
     * @param driverId
     * @param memberId
     */
    @Transactional
    public void send_order_mall_web(Long orderId,Long driverId, Long memberId){

        KitchenOrder order=checkOrder(orderId,SundayCommonConstants.ORDER_STATUS_DPS,"非待配送订单，不能发货",null);
        order.setOrderStatus(SundayCommonConstants.ORDER_STATUS_PSZ);
        order.setSendTime(new Date());
        //设置配送员信息(非)
        if(LongUtil.isNotZreo(driverId)){
            SundayMember driver =memberService.getById(driverId);
            order.setDriverId(driver.getId());
            order.setDriverName(driver.getNickName());
            order.setDriverMobile(driver.getMobile());
        }
        //memberId作为(员工)经办人
        if(LongUtil.isNotZreo(memberId)){
            SundayMember member =memberService.getById(memberId);
            order.setHandleId(memberId);
            order.setHandleName(member.getNickName());
        }
        super.update(order);
    }
}
